#  Copyright (c) 2010
#  The Regents of the University of Michigan
#  All Rights Reserved

#  Permission is granted to use, copy, create derivative works, and
#  redistribute this software and such derivative works for any purpose,
#  so long as the name of the University of Michigan is not used in
#  any advertising or publicity pertaining to the use or distribution
#  of this software without specific, written prior authorization. If
#  the above copyright notice or any other identification of the
#  University of Michigan is included in any copy of any portion of
#  this software, then the disclaimer below must also be included.

#  This software is provided as is, without representation or warranty
#  of any kind either express or implied, including without limitation
#  the implied warranties of merchantability, fitness for a particular
#  purpose, or noninfringement.  The Regents of the University of
#  Michigan shall not be liable for any damages, including special,
#  indirect, incidental, or consequential damages, with respect to any
#  claim arising out of or in connection with the use of the software,
#  even if it has been or is hereafter advised of the possibility of
#  such damages.

# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.utils.encoding import smart_str
import django.db

import urllib

TABLE_NAME = 'torrent_descs'
def search(request):
  search_string = request.GET.get('q')
  results = []
  if search_string:
    cursor = django.db.connection.cursor()
    cursor.execute('''SELECT * FROM (SELECT DISTINCT ON (hash) name, hash, size, seeders, leechers,
                      ts_rank_cd(to_tsvector('english', name), query, 0) AS rank,
                      COALESCE(seeders, 0) + COALESCE(leechers, 0) as myrank
                      FROM ' + TABLE_NAME + ', plainto_tsquery('english', %s) AS query
                      WHERE to_tsvector('english', name) @@ query AND hash is not NULL
                      AND COALESCE(seeders, 1) <> 0) AS results
                      ORDER BY results.myrank DESC NULLS LAST LIMIT 100''',
                   [search_string])
#    cursor.execute('''SELECT distinct name,hash FROM torrent_descs
# WHERE name=%s and hash is not NULL''',
#                   [search_string])
    results = [(name, 'magnet:?xt=urn:btih:%s&dn=%s' % 
                (str(hash).encode('hex'), urllib.quote_plus(smart_str(name, errors='ignore'))),
                size, seeders, leechers, rank, myrank)
               for (name, hash, size, seeders, leechers, rank, myrank) in cursor.fetchmany(100)]

  return render_to_response('results.html', {'q': search_string, 'results': results})


def index(request):
  return render_to_response('index.html', {})
